package com.unicom_ng.rfid;

import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;

import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.widget.Toast;
import android.os.Handler;
import android.os.Message;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.rfid.rxobserver.bean.RXInventoryTag;
import java.util.Map;
import android.util.Log;
import java.util.HashMap;
import android.provider.Settings;

import androidx.annotation.RequiresApi;

import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.modules.core.DeviceEventManagerModule;

import com.module.interaction.RXTXListener;
import com.module.interaction.ModuleConnector;
import com.nativec.tools.ModuleManager;
import com.rfid.RFIDReaderHelper;
import com.rfid.ReaderConnector;
import com.rfid.rxobserver.RXObserver;
import com.rfid.rxobserver.bean.RXInventoryTag;
import com.xdl2d.scanner.TDScannerConnector;
import com.xdl2d.scanner.TDScannerHelper;
import com.xdl2d.scanner.callback.RXCallback;

import java.util.Arrays;
import com.util.StringTool;

import static android.media.RingtoneManager.TYPE_NOTIFICATION;

public class InfraredModule extends ReactContextBaseJavaModule {
    private final static int SCAN_OVER = 2;
    private final static int SCAN_FAIL = 0;
    private final static int SCAN_REVEICE = 1;
    private final static String UNINIT_STATE="uninit"; // 未初始化
    private final static String INIT_STATE="init"; // 已初始化
    private final static String DESTORY_STATE="destory"; // 已释放
    private static final String DURATION_SHORT_KEY = "SHORT";
    private static final String DURATION_LONG_KEY = "LONG";
    ReactApplicationContext reactContext;
    private String[] rfidType = new String[0];
    private Map<String,RXInventoryTag> rfidSet = new HashMap<>();
    private final static String FIND_HANDLE_KEY="find";
    private final static String SCAN_HANDLE_KEY="scan";
    private String currentHandleType = SCAN_HANDLE_KEY;
    private String currentFindRfid = null;
    private BeepManager been;
    private String state = UNINIT_STATE; // rfid模块状态
    Uri notification = RingtoneManager.getDefaultUri(TYPE_NOTIFICATION);
    Ringtone r;

    static ModuleConnector mConnector = new TDScannerConnector();
    static TDScannerHelper mScanner;
    static InfraredModule instance;

    public InfraredModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext=reactContext;
        instance=this;
    }

    /**
     * 二维
     */
    //RXCallback ref = (bytes) -> {};
    private RXCallback callback = new RXCallback() {
        public void callback(byte[] bytes) {
            Log.d("2D",new String(bytes));
            beep(1F);
            WritableArray writableArray = new WritableNativeArray();
            writableArray.pushString(new String(bytes));
            sendEvent(InfraredModule.this.reactContext, "onInfraredReveice", writableArray);
        }
    };

    public static String byteArrToHexString(byte[] b) {
		return byteArrToHexString(b,false);
	}
	
	/**
	 * 字节转16进制字符串
	 * @param b			源字节数组
	 * @param isFormat	转换的字符串是否每两个字节+一个空格
	 * @return
	 */
	public static String byteArrToHexString(byte[] b,boolean isFormat) {
		String result = "";
		if(b!=null){
			for (int i = 0; i < b.length; i++) {
				result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
			}
		}
		if(isFormat) {
			String regex = "(.{2})";
	        return result.toUpperCase().replaceAll (regex, "$1 ");
		}else {
			return result.toUpperCase();
		}
    }
    
    private void initScanner() {
        ModuleManager.newInstance().setScanStatus(true);
        mScanner = TDScannerHelper.getDefaultHelper();
        if(mScanner != null && state == UNINIT_STATE){
            mScanner.regist2DCodeData(callback);
        }
    }

    @Override
    public String getName() {
        return "InfraredModule";
    }

    @ReactMethod(isBlockingSynchronousMethod = true)
    public String getState() {
        return state;
    }

    @ReactMethod
    public void init() {
        if(been==null){
            been=new BeepManager(reactContext);
        }
        initScanner();
        
        state=INIT_STATE;
    }

    @ReactMethod
    public void destory() {
        state=UNINIT_STATE;
        ModuleManager.newInstance().setScanStatus(false);
        
    }
    
    public static boolean create(){
        Log.d("2D","连接了红外设备");
        return mConnector.connectCom("dev/ttyS1", 9600);
    }

    public static void release(){
        Log.d("2D","释放了红外设备");
        if (mConnector != null) {
            mConnector.disConnect();
        }
        ModuleManager.newInstance().setScanStatus(false);
        ModuleManager.newInstance().release();
    }

    @ReactMethod
    public void scan() {
        currentHandleType=SCAN_HANDLE_KEY;
        if(mScanner!=null){
            mScanner.sendBuffer(new byte[]{(byte)0x1b,(byte)0x31});
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.P)
    @ReactMethod
    public void beep(float volume) {
        try {
            been.playBeepSoundAndVibrate(volume,volume);
        } catch (Exception e) {
            System.out.println("播放异常:"+e.getMessage());
            e.printStackTrace();
        }
    }

    //定义发送事件的函数
    public void sendEvent(ReactContext reactContext, String eventName, WritableArray params)
    {
        reactContext
                .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                .emit(eventName,params);
    }
}